package com.aiapphub.BaseCode.config;

import com.aiapphub.BaseCode.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 注入 JwtAuthenticationFilter，用于处理 JWT 认证
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    // 注入自定义的 AuthenticationEntryPoint，用于处理未认证的请求
    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;

    // 注入自定义的 AccessDeniedHandler，用于处理认证后的拒绝访问情况
    @Autowired
    AccessDeniedHandler accessDeniedHandler;

    // 创建一个认证管理器
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        // 返回 Spring Security 默认的 AuthenticationManager 实例
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭 CSRF（跨站请求伪造）保护，通常在使用 Token 认证时关闭
                .csrf().disable()
                // 配置 Session 管理
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 设定 Session 为无状态，不会创建和使用 Session
                .and()
                .authorizeRequests()
                // 允许登录接口匿名访问
                .antMatchers("/api/user/login", "/api/user/register", "/api/user/logout").anonymous()
                // 允许获取当前用户信息接口访问（需要认证，但通过JWT Filter处理）
                .antMatchers("/api/system/user/**").permitAll()
                // 允许Swagger文档相关接口匿名访问
                .antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").anonymous()
                // 其他所有请求都需要认证
                .anyRequest().authenticated();

        // 配置异常处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint) // 未认证请求的处理器
                .accessDeniedHandler(accessDeniedHandler); // 已认证但访问被拒绝的处理器

        // 关闭默认的注销功能
        http.logout().disable();

        // 将自定义的 JWT 认证过滤器添加到 Spring Security 过滤器链中
        // 确保 JWT 过滤器在 UsernamePasswordAuthenticationFilter 之前执行
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        // 允许跨域请求
        http.cors();
    }

    // 对密码进行编码和验证，使用 BCrypt 算法
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 返回一个 BCryptPasswordEncoder 实例
        return new BCryptPasswordEncoder();
    }
}
